<script setup>
import { Message, MessageBox } from 'element-ui';
import { merge, forEach, pick } from 'lodash-es';
import { getToken } from '@/utils/auth';
import { useGlobalState } from '@/store/globalState.js';
import { useRequest } from '@/hooks/requestHooks.js';
import { useWatch } from '@/hooks/useWatch.js';
import {
  getInfo,
  getEnergyHistory,
  getAllBuilding,
  getOneEnterprise,
  getKxxbgLists,
  getList,
  getReportTree,
  updateReport,
  getKxxbgData,
  saveQuestionnaire,
  removeReport,
} from '@/api/index.js';
import { useResetForm } from '@/hooks/tool.js';
import EnterpriseTree from '@/components/EnterpriseInfo/EnterpriseTree.vue';
import CfInfoList from '@/views/xmgl/components/CfInfoList.vue';
import DataImport from '@/components/DataImport/index.vue';

const active = ref(1);
const kxxbgUoloadForm = ref(null);

const activeName = ref('lists');
const szxxUploadUrl = useGlobalState().globalState.fileUrl + '/entrust/questionnaire/importData';
const queryParams = ref({
  enterpriseCode: '',
  buildingCode: '',
});
const monthLists = Array.from({ length: 12 }, (_, idx) => (idx < 9 ? `0${idx + 1}` : `${idx + 1}`));
const waterYearlists = ref([]);
const eleYearlists = ref([]);
const gasYearlists = ref([]);
const waterTableData = ref([]);
const eleTableData = ref([]);
const gasTableData = ref([]);
const res = ref({});
const kxxbgDetailsBuild = ref([]);
const szSaveButton = ref(false);
const reportTable = ref(null);
const open = ref(false);
const opentitle = ref('');
const kxxbgDetailsData = ref(null);
//上传报告的from
const form = ref({
  enterpriseCode: '',
  buildingCode: '',
  reportCode: '',
});
//报告table的form
const tableForm = ref({
  enterpriseCode: '',
  pageNum: 1,
  pageSize: 10,
});
const isShow = ref(false);
const openUrl = ref('');
const OpenKxxbg = () => {
  open.value = true;
  opentitle.value = '上传';
};
const [szxqTree] = useRequest(getAllBuilding, {});
const [scbgTree, treeLoading, scbgTreeRun] = useRequest(getOneEnterprise, {
  defaultParams: [{ enterpriseCode: '1' }],
  manual: true,
  onSuccess: data => {},
});
let [, loading, run] = useRequest(getInfo, {
  defaultParams: [queryParams.value],
  manual: true,
  onSuccess: data => {
    if (data.data) {
      res.value = data.data;
    } else {
      res.value = {};
    }
  },
});
const [energyLists, loading2, run2] = useRequest(getEnergyHistory, {
  defaultParams: [queryParams.value],
  manual: true,
});
const [reportTree, , reportRun] = useRequest(getReportTree, {
  defaultParams: [],
  manual: true,
});
const [, , kxxbgDetailsRun] = useRequest(getKxxbgData, {
  defaultParams: [],
  manual: true,
  onSuccess: data => {
    let arr = [];
    forEach(data.data.prbList, el => {
      if (el.level > 1) {
        arr.push(el.buildingCode);
      }
    });
    kxxbgDetailsBuild.value = arr;
  },
});
const [, , saveQuestionnaireRun] = useRequest(saveQuestionnaire, {
  defaultParams: [],
  manual: true,
  onSuccess: data => {
    if (data.code === 200) {
      Message.success('保存成功');
      cancel();
      kxxbgDetailsBuild.value = [];
      let formdata = new FormData(); //new出来的对象
      formdata.append('enterpriseCode', queryParams.value.enterpriseCode);
      formdata.append('buildingCode', queryParams.value.buildingCode);
      run(formdata);
      run2(formdata);
      szSaveButton.value = false;
    }
  },
});
const [editKxxbgData, , editKxxbgRun] = useRequest(updateReport, {
  defaultParams: [],
  manual: true,
  onSuccess: data => {
    if (data.code === 200) {
      Message.success('编辑成功');
      cancel();
      kxxbgDetailsBuild.value = [];
      let obj = handleQuery(tableForm.value);
      kxxbgTableRun(obj);
    }
  },
});
const [kxxbgTableData, kxxbgLoading, kxxbgTableRun] = useRequest(getKxxbgLists, {
  defaultParams: [],
  manual: true,
  onSuccess: data => {
    reportTree.value = [];
  },
});
const [, , removeReportRun] = useRequest(removeReport, {
  defaultParams: [],
  manual: true,
  onSuccess: data => {
    Message.success('删除成功');
    let obj = handleQuery(tableForm.value);
    kxxbgTableRun(obj);
  },
});
const handleQuery = params => {
  let formdata = new FormData(); //new出来的对象
  Object.keys(params).forEach(key => {
    formdata.append(key, params[key]);
  });
  return formdata;
};
const changeButton = val => {
  active.value = val;
  if (val === 2) {
    let obj = handleQuery(tableForm.value);
    kxxbgTableRun(obj);
  }
};
const handleNodeClick = params => {
  szSaveButton.value = false;
  queryParams.value = merge(queryParams.value, params);
  let formdata = new FormData(); //new出来的对象
  formdata.append('enterpriseCode', queryParams.value.enterpriseCode);
  // debugger;
  if (params.value?.buildingCode) {
  } else {
    formdata.append('buildingCode', queryParams.value.buildingCode);
  }
  run(formdata);
  run2(formdata);
};

const filterTableData = (data, year) => {
  const tableData = [];
  for (let i = 0; i < monthLists.length; i++) {
    const result = {};
    Reflect.set(result, 'month', monthLists[i]);
    forEach(data, el => {
      if (el.usageTime.substring(5, 7) === monthLists[i]) {
        forEach(year, e => {
          if (el.usageTime.substring(0, 4) === e) {
            Reflect.set(result, `${e}energyQuantity`, el.energyQuantity);
            Reflect.set(result, `${e}cost`, el.cost);
          }
        });
      }
    });
    tableData.push(result);
  }
  return tableData;
};
useWatch(scbgTree, n => {
  forEach(n, e => {
    e.disabled = true;
  });
});
const editKxxbgTable = (row, index) => {
  open.value = true;
  opentitle.value = '编辑';
  form.value.enterpriseCode = row.enterpriseCode;
  form.value.reportCode = row.reportCode;
  const obj = pick(form.value, ['enterpriseCode']);
  scbgTreeRun(obj);
  let formdata = new FormData(); //new出来的对象
  formdata.append('code', row.reportCode);
  kxxbgDetailsRun(formdata);
  // reportRun({ reportCode: row.reportCode });
  // scbgTree.value = reportTree.value;
  if (row.reportFileName && row.reportFileUrl) {
    fileLists.value = [
      {
        name: row.reportFileName,
        url: useGlobalState().globalState.fileUrl + row.reportFileUrl,
        originalUrl: row.reportFileUrl,
      },
    ];
  }
};
const filterValue = (row, year, val) => {
  for (let i in row) {
    if (i == year + val) {
      return row[i];
    }
  }
};
const [enterpriseList, enterpriseListLoading] = useRequest(getList, {
  defaultParams: [{ enterpriseName: '' }],
});

const changeTableEnterprise = () => {
  let obj = handleQuery(tableForm.value);
  kxxbgTableRun(obj);
};
const changeEnterprise = val => {
  form.value.enterpriseCode = val;
  kxxbgUoloadForm.value.validateField('enterpriseCode');
  fileLists.value = [];
  const obj = pick(form.value, ['enterpriseCode']);
  scbgTreeRun(obj);
};
const upload = ref(null);
const uploadList = ref({
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: useGlobalState().globalState.fileUrl + '/entrust/feasibilityReport/add',
  // url2: useGlobalState().globalState.fileUrl + '/entrust/feasibilityReport/update',
});
const fileLists = ref([]);
const handleCheckChange = params => {
  form.value.buildingCode = params;
};
//上传前的回调
const handleFileMainUpload = file => {};
// 超出限制上传数量回调
const handleExceed = () => {
  Message({
    type: 'warning',
    message: '当前限制最大上传数量：1 ,上传新的文件之前请先删除原文件！',
  });
};
const handleRemove = (file, fileList) => {
  fileLists.value = [];
};
const handleFileSuccess = data => {
  res.value = data?.questionnaire ?? {};
  energyLists.value.rows = data?.usageEnergy ?? [];
  szSaveButton.value = true;
};
const handleAvatarErroe = (err, file, fileList) => {
  Message({
    type: 'error',
    message: err?.msg ?? '上传失败，请重新上传',
  });
  fileLists.value.splice(0, 1);
  upload.value.clearFiles();
};
const handleUploadChange = (file, fileList) => {
  fileLists.value = fileList;
};
const submitForm = () => {
  kxxbgUoloadForm.value.validate(valid => {
    if (valid) {
      if (opentitle.value === '上传') {
        if (fileLists.value.length <= 0) {
          Message.error('请上传文件！');
        } else {
          if (opentitle.value === '上传') {
            upload.value.submit();
          }
        }
      } else {
        if (fileLists.value.length > 0) {
          if (fileLists.value[0].url) {
            const formdatas = new FormData(); //new出来的对象
            formdatas.append('file', '');
            formdatas.append('reportCode', form.value.reportCode);
            formdatas.append('buildingCode', form.value.buildingCode);
            formdatas.append('enterpriseCode', form.value.enterpriseCode);
            editKxxbgRun(formdatas);
          } else {
            upload.value.submit();
          }
        } else {
          Message.error('请上传文件！');
        }
      }
    } else {
      return false;
    }
  });
};
const handleAvatarSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    Message.success(opentitle.value + '成功');
    cancel();
    let obj = handleQuery(tableForm.value);
    kxxbgTableRun(obj);
  } else {
    Message({
      type: 'error',
      message: response.msg,
    });
    fileLists.value.splice(0, 1);
    upload.value.clearFiles();
  }
};
const cancel = () => {
  // useResetForm(kxxbgUoloadForm.value);
  form.value = { enterpriseCode: '' };
  upload.value.clearFiles();
  open.value = false;
  scbgTree.value = [];
  kxxbgDetailsBuild.value = [];
};
const select = (selection, row) => {
  if (selection.length > 1) {
    const del_row = selection.shift();
    reportTable.value.toggleRowSelection(del_row, false);
    reportRun({ reportCode: selection[0].reportCode });
  } else if (selection.length === 1) {
    reportRun({ reportCode: selection[0].reportCode });
  } else if (selection.length === 0) {
    reportTree.value = [];
  }
};
const handleSelectionChange = val => {
  // reportRun({ reportCode: val[0].reportCode });
};
const handleRowClick = (row, column, event) => {
  forEach(kxxbgTableData.value.rows, n => {
    if (n.reportCode === row.reportCode && n.createTime === row.createTime) {
      reportTable.value.toggleRowSelection(n, true);
      reportRun({ reportCode: n.reportCode });
    } else {
      reportTable.value.toggleRowSelection(n, false);
    }
  });
};
const handleSave = params => {
  let obj = {
    enQuestionnaire: params,
    usageEnergy: energyLists.value?.rows ?? [],
  };
  saveQuestionnaireRun(obj);
};
const handlePreview = () => {
  isShow.value = true;
  openUrl.value = fileLists.value[0].url;
};
const deleteKxxbgTable = (row, index) => {
  MessageBox.confirm('是否删除', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      let formdata = new FormData();
      formdata.append('reportCode', row.reportCode);
      removeReportRun(formdata);
    })
    .catch(() => {});
};
const withDraw = () => {
  let formdata = new FormData(); //new出来的对象
  formdata.append('enterpriseCode', queryParams.value.enterpriseCode);
  formdata.append('buildingCode', queryParams.value.buildingCode);
  run(formdata);
  run2(formdata);
};
useWatch(
  energyLists,
  n => {
    const obj = {
      ele: [],
      water: [],
      gas: [],
    };
    n.rows.forEach(item => {
      if (item.energyType === '电' || item.energyType === 'ELECTRICITY') {
        obj.ele.push(item);
        if (eleYearlists.value.indexOf(item.usageTime.substring(0, 4)) === -1) {
          eleYearlists.value.push(item.usageTime.substring(0, 4));
        }
      } else if (item.energyType === '水' || item.energyType === 'WATER') {
        obj.water.push(item);
        if (waterYearlists.value.indexOf(item.usageTime.substring(0, 4)) === -1) {
          waterYearlists.value.push(item.usageTime.substring(0, 4));
        }
      } else if (item.energyType === '气' || item.energyType === 'AIR') {
        obj.gas.push(item);
        if (gasYearlists.value.indexOf(item.usageTime.substring(0, 4)) === -1) {
          gasYearlists.value.push(item.usageTime.substring(0, 4));
        }
      }
    });
    eleTableData.value = filterTableData(obj.ele, eleYearlists.value);
    waterTableData.value = filterTableData(obj.water, waterYearlists.value);
    gasTableData.value = filterTableData(obj.gas, gasYearlists.value);
  },
  { deep: true },
);
useWatch(opentitle, n => {
  if (n === '上传') {
    uploadList.value.url = useGlobalState().globalState.fileUrl + '/entrust/feasibilityReport/add';
  } else if (n === '编辑') {
    uploadList.value.url = useGlobalState().globalState.fileUrl + '/entrust/feasibilityReport/update';
  }
});
</script>
<template>
  <div class="u-df-st architecture-box">
    <div class="architecture-left u-base-fg u-h100 u-br20 u-border-bg">
      <div class="u-df-se u-mt20">
        <el-button
          type="primary"
          plain
          size="small"
          @click="changeButton(1)"
          :style="{ background: active === 1 ? '#068bba' : '', color: active === 1 ? '#fff' : '' }"
        >
          收资详情
        </el-button>
        <el-button
          type="primary"
          plain
          size="small"
          @click="changeButton(2)"
          :style="{ background: active === 2 ? '#068bba' : '', color: active === 2 ? '#fff' : '' }"
        >
          可行性报告
        </el-button>
      </div>
      <EnterpriseTree
        class="tree"
        v-show="active === 1"
        :data="szxqTree"
        :showFilter="true"
        @handleNodeClick="handleNodeClick"
        :defaultExpand="false"
        :szSaveButton="szSaveButton"
      />
      <div v-show="active === 2">
        <div class="u-m20 prompt u-fs12 u-df-st">
          <i class="el-icon-info u-ml10 u-mr10"></i>
          报告关联区域
        </div>
        <EnterpriseTree class="tree" :data="reportTree" />
      </div>
    </div>
    <div class="architecture-right u-base-fg u-h100 u-p20">
      <div v-show="active === 1">
        <el-tabs v-model="activeName" class="u-base-fg">
          <el-tab-pane label="收资清单" name="lists">
            <CfInfoList :formData="res" @handleSave="handleSave" @withDraw="withDraw" :showSave="szSaveButton" />
          </el-tab-pane>
          <el-tab-pane label="用水数据" name="water" class="u-m20" lazy>
            <el-table :data="waterTableData" v-loading="loading2" border>
              <el-table-column prop="month" label="月份"></el-table-column>
              <el-table-column v-for="item in waterYearlists" :key="item" :label="item" align="center">
                <el-table-column prop="energyQuantity" label="用水量(t）">
                  <template slot-scope="scope">
                    <span>{{ filterValue(scope.row, item, scope.column.property) | nullishCoalescing }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="cost" label="水费(元）">
                  <template slot-scope="scope">
                    <span>{{ filterValue(scope.row, item, scope.column.property) | nullishCoalescing }}</span>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="用电数据" name="electricity" class="u-m20" lazy>
            <el-table :data="eleTableData" v-loading="loading2" border>
              <el-table-column prop="month" label="月份">
                <!-- <template slot-scope="scope">{{}}</template> -->
              </el-table-column>
              <el-table-column v-for="item in eleYearlists" :key="item" :label="item" align="center">
                <el-table-column prop="energyQuantity" label="用电量(kW∙h）">
                  <template slot-scope="scope">
                    <span>{{ filterValue(scope.row, item, scope.column.property) | nullishCoalescing }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="cost" label="电费(元）">
                  <template slot-scope="scope">
                    <span>{{ filterValue(scope.row, item, scope.column.property) | nullishCoalescing }}</span>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="用气数据" name="gas" class="u-m20" lazy>
            <el-table :data="gasTableData" v-loading="loading2" border>
              <el-table-column prop="month" label="月份"></el-table-column>
              <el-table-column v-for="item in gasYearlists" :key="item" :label="item" align="center">
                <el-table-column prop="energyQuantity" label="用气量(m³）">
                  <template slot-scope="scope">
                    <span>{{ filterValue(scope.row, item, scope.column.property) | nullishCoalescing }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="cost" label="气费(元）">
                  <template slot-scope="scope">
                    <span>{{ filterValue(scope.row, item, scope.column.property) | nullishCoalescing }}</span>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <div class="buttonBox">
          <DataImport
            :onlyShowBtn="true"
            title="收资信息"
            templateTit="收资信息.xlsx"
            :uploadUrl="szxxUploadUrl"
            :extraParams="queryParams"
            downloadUrl="/businessbase/dataImportTemplate/download"
            pageParams="EN_SZ"
            @handleFileSuccess="handleFileSuccess"
          />
        </div>
      </div>
      <div v-show="active === 2">
        <el-button icon="el-icon-upload2" type="primary" plain size="small" @click="OpenKxxbg">
          点击上传附件报告
        </el-button>
        <el-form :model="tableForm" ref="kxxbgForm" size="small" label-width="100px" class="uploadForm u-mt20">
          <el-form-item label="企业名称：" prop="enterpriseCode">
            <el-select
              v-model="tableForm.enterpriseCode"
              placeholder="请选择企业"
              :loading="enterpriseListLoading"
              @change="changeTableEnterprise"
              clearable
            >
              <el-option
                v-for="item in enterpriseList"
                :key="item.enterpriseCode"
                :label="item.enterpriseName"
                :value="item.enterpriseCode"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <el-table
          class="u-mt20"
          ref="reportTable"
          v-loading="kxxbgLoading"
          :data="kxxbgTableData?.rows ?? []"
          height="550"
          @selection-change="handleSelectionChange"
          @select="select"
          @row-click="handleRowClick"
        >
          <el-table-column type="selection" width="50px" />
          <el-table-column prop="reportFileName" label="报告文件" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="createTime" label="上传时间"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <span>
                <el-button size="small" type="text" @click="editKxxbgTable(scope.row, scope.$index)">编辑</el-button>
                <el-button size="small" type="text" @click="deleteKxxbgTable(scope.row, scope.$index)">删除</el-button>
              </span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          :total="kxxbgTableData?.total ?? 0"
          :page.sync="tableForm.pageNum"
          :limit.sync="tableForm.pageSize"
          @pagination="changeTableEnterprise"
        />
        <!-- :total="kxxbgTableData?.total" -->
        <el-dialog :visible.sync="open" width="40%" :before-close="cancel" append-to-body>
          <div slot="title" class="dialog-title">
            <span class="tit">{{ opentitle }}-报告</span>
          </div>
          <el-form :model="form" ref="kxxbgUoloadForm" size="small" label-width="100px" class="uploadForm">
            <el-form-item
              label="企业名称："
              prop="enterpriseCode"
              :rules="{ required: true, message: '请选择企业名称', trigger: 'blur' }"
            >
              <el-select
                :loading="enterpriseListLoading"
                v-model="form.enterpriseCode"
                placeholder="请选择企业"
                @change="changeEnterprise"
              >
                <el-option
                  v-for="item in enterpriseList"
                  :key="item.enterpriseCode"
                  :label="item.enterpriseName"
                  :value="item.enterpriseCode"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <EnterpriseTree
            class="tree"
            :data="scbgTree"
            :showCheckbox="true"
            @handleCheckChange="handleCheckChange"
            :defaultCheckedKeys="kxxbgDetailsBuild"
          />
          <div slot="footer" class="dialog-footer" style="position: relative">
            <el-upload
              class="upload-demo u-ml10"
              ref="upload"
              accept=".pdf"
              :action="uploadList.url"
              :headers="uploadList.headers"
              :data="form"
              :before-upload="handleFileMainUpload"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarErroe"
              :on-change="handleUploadChange"
              :on-remove="handleRemove"
              multiple
              :file-list="fileLists"
              :auto-upload="false"
              :limit="1"
              :on-exceed="handleExceed"
            >
              <el-button size="small" plain class="el-icon-upload2" type="primary" style="font-size: 14px">
                点击上传报告
              </el-button>
            </el-upload>
            <el-button
              v-if="opentitle === '编辑'"
              style="position: absolute; top: 0; right: 0; font-size: 14px"
              size="small"
              plain
              type="primary"
              @click="handlePreview"
            >
              文件预览
            </el-button>
            <el-dialog
              title="文件预览"
              top="50px !important"
              :visible="isShow"
              @close="isShow = false"
              width="90%"
              append-to-body
            >
              <iframe :src="openUrl" width="100%" height="800px" style="border: 0">111 {{ openUrl }}</iframe>
            </el-dialog>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button size="small" @click="cancel" type="primary" plain>取 消</el-button>
            <el-button type="primary" size="small" @click="submitForm">保 存</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
@import url(../css/index.scss);
.tree {
  height: calc(100% - 52px);
}

.architecture-right {
  position: relative;
  .buttonBox {
    position: absolute;
    top: 20px;
    right: 20px;
  }
}
.uploadForm ::v-deep .el-form-item--small.el-form-item {
  margin-bottom: 0;
}
::v-deep .el-upload,
.el-upload--text {
  width: 100%;
  text-align: left;
}
.upload-demo ::v-deep .el-upload-list {
  text-align: left;
  margin-left: 0px;
}
::v-deep .el-dialog__footer {
  height: 100%;
}
::v-deep .el-table__header-wrapper .el-checkbox {
  display: none;
}
</style>
